package concurrent.util;

import java.util.concurrent.Exchanger;

/**
 * \* User: Administrator
 * <p>
 * \* Date: 2020/11/26
 * <p>
 * \* Time: 14:12
 * <p>
 * \* Description:
 * \
 */
public class ExchangeDemo {
    static final Exchanger<String> exchanger = new Exchanger<>();

    public static void main(String[] args) {
        new Thread(()->{
            String name = Thread.currentThread().getName();
            System.out.println(name + "开始执行");
            try {
                Thread.sleep(2000);
                String fromT2 = exchanger.exchange("From T1");
                System.out.println(name + "接收到的数据：" + fromT2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"T1").start();

        new Thread(()->{
            String name = Thread.currentThread().getName();
            System.out.println(name + "开始执行");
            try {
                Thread.sleep(3000);
                String fromT1 = exchanger.exchange("From T2");
                System.out.println(name + "接收到的数据：" + fromT1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "T2").start();

        System.out.println("......");
    }
}
